package com.adam.blog.common.aop;

import com.adam.blog.utils.HttpContextUtils;
import com.adam.blog.utils.IpUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Component
@Aspect //切面    定义了通知和切点的关系
@Slf4j
public class LogAspect {

    @Pointcut("@annotation(com.adam.blog.common.aop.LogAnnotation)")   //切点位置
    public void pt(){}

    //环绕通知  对方法前后都可以增强
    @Around("pt()")  //通知类   标识切点
    public Object log(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        //接收日志代码

        long beginTime = System.currentTimeMillis();
        //执行方法
        Object result = proceedingJoinPoint.proceed();
        //执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        //保存日志
        recordLog(proceedingJoinPoint, time);
        return result;
    }

    private void recordLog(ProceedingJoinPoint proceedingJoinPoint, long time) {
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        Method method = signature.getMethod();
        LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
        log.info("=====================log start================================");
        log.info("module:{}",logAnnotation.module());
        log.info("operator:{}",logAnnotation.operator());

        //请求的方法名
        String className = proceedingJoinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        log.info("request method:{}",className + "." + methodName + "()");

        //请求的参数
        Object[] args = proceedingJoinPoint.getArgs();
        String params = JSON.toJSONString(args[0]);
        log.info("params:{}",params);

        //获取request 设置IP地址
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        log.info("ip:{}", IpUtils.getIpAddr(request));


        log.info("excute time : {} ms",time);
        log.info("=====================log end================================");

    }
}
